<template>
  <view
    :style="{
      position: isSticky ? 'sticky' : 'static',
      top: isSticky ? stickyTop : 0,
      backgroundColor,
      zIndex: zIndex,
    }"
  >
    <slot />
  </view>
</template>

<script lang="ts">
  import { defineComponent, provide, ref, watch, nextTick, type PropType } from 'vue';

  import { propTypes } from '@/utils/propTypes';
  import { onPageScroll } from '@dcloudio/uni-app';

  export default defineComponent({
    props: {
      modelValue: [Number, String],
      isSwiper: propTypes.bool.def(false),
      isSticky: propTypes.bool.def(false),
      stickyTop: propTypes.string.def('0px'),
      backgroundColor: propTypes.string,
      isScrollTop: propTypes.bool.def(true),
      zIndex: propTypes.number.def(98),
    },
    emits: ['register', 'update:modelValue', 'change'],
    setup(_, { emit }) {
      const index = ref<string>(_.modelValue as string);
      const tabs = ref<any[]>([]);
      const page_this = ref<any>(null);

      const tabsScrollTop: {
        [x: string]: any;
      } = {};

      function addtabs(item: any) {
        tabs.value.push(item);
      }

      function PageScroll({ scrollTop }: any) {
        tabsScrollTop[index.value] = scrollTop;
      }

      function setPageThis(p_this: any) {
        page_this.value = p_this;
      }

      if (!_.isSwiper) {
        onPageScroll(PageScroll);
      }

      watch(
        (): string => _.modelValue as string,
        (val) => {
          index.value = val;
        },
      );

      watch(index, (v) => {
        emit('update:modelValue', v);
        emit('change', v);
        if (!_.isSwiper && _.isScrollTop) {
          nextTick(() => {
            uni.pageScrollTo({
              scrollTop: tabsScrollTop[v] || 0,
              duration: 0,
            });
          });
        }
      });

      provide('tab_list', tabs);
      provide('tab_index', index);
      provide('tab_addtabs', addtabs);
      provide('tab_page_this', page_this);

      emit('register', {
        setPageThis,
      });
      return {
        tabs,
        index,
      };
    },
  });
</script>
<style lang="scss" scoped></style>
